(function($) {
	"use strict";

	var ProductType = function(options) {
		this.init('product_type', options, ProductType.defaults);
		this.major_types = function(major_types){
			var result = {};
			$.each(major_types, function(){
				result[this.id] = this;
			});
			return result;
		}(options.major_types);
		this.minor_types = function(minor_types){
			var result = {};
			$.each(minor_types, function(){
				result[this.id] = this;
			});
			return result;
		}(options.minor_types);
	};

	$.fn.editableutils.inherit(ProductType, $.fn.editabletypes.abstractinput);

	$.extend(ProductType.prototype, {

		render : function() {
			this.$tpl.find('[name="major_id"]').select2({
				data: this.options.major_types,
			});
			this.$input = this.$tpl.find('select');
		},

		value2html : function(value, element) {
			if (!value) {
				$(element).empty();
				return;
			}
			var minor_type = this.minor_types[value];
			var major_type = minor_type.majorType;
			var html = $('<div>').text(major_type.name).html() + ' / ' + $('<div>').text(minor_type.name).html();
			$(element).html(html);
		},

		html2value : function(html) {
			return null;
		},

		value2str : function(value) {
			return value;
		},

		str2value : function(str) {
			return str;
		},

		value2input : function(value) {
			if (!value) {
				return;
			}
			var major_id = this.minor_types[value].majorType.id;
			this.$input.filter('[name="major_id"]')
				.val(major_id)
				.trigger('change');
			this.$input.filter('[name="minor_id"]').select2({
				data: this.options.minor_types_by_major[major_id],
			}).val(value).trigger('change');
		},

		input2value : function() {
			return this.$input.filter('[name="minor_id"]').select2('val');
		},

		activate : function() {
			this.$input.filter('[name="major_id"]').focus();
		},

		autosubmit : function() {
			this.$input.keydown(function(e) {
				if (e.which === 13) {
					$(this).closest('form').submit();
				}
			});
		}
	});

	ProductType.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
		tpl: '<div class="editable-product_type form-group">' +
			'<select name="major_id" class="form-control"></select>' +
			'<select name="minor_id" class="form-control"></select>' +
		'</div>',
		major_types: [],
		minor_types: [],
		minor_types_by_major: {}
	});
	
	$.fn.editabletypes.product_type = ProductType;

}(window.jQuery));